var endpoint = "";
var bucket = "";
var accessKeyId = "";
var secretAccessKey = "";
var sessionToken = "";
var file;
var fileInput = document.querySelector('#fileInput');

fileInput.addEventListener("change", function () {
    file = this.files[0];
});

/**
 * 查询bucket中的对象
 */
function queryObjects() {
    s3 = createCredentialsS3Client();
    var params = {
        Bucket: bucket,
        MaxKeys: 10,  //展示记录数
        Prefix: $("#fileName").val()  //只支持从key的开始位置进行模糊查找
    };
    s3.listObjectsV2(params, function (err, data) {
        if (err) {
            console.log(err, err.stack);
        } else {
            console.log(data);
            var html = [];
            for (var i = 0; i < data.Contents.length; i++) {
                var object = data.Contents[i];
                html.push("<tr>");
                html.push("<td>" + object.Key + "</td>");
                html.push("<td>" + object.Size + "</td>");
                html.push("<td>" + object.LastModified + "</td>");
                html.push("</tr>");
            }
            $("#fileList").html(html.join(""));
        }
    });
}

/**
 * 上传文件
 */
function uploadFile() {
    s3 = createCredentialsS3Client();
    var params = {
        ACL: "public-read",  //对所有用户开放可读权限
        Bucket: bucket,
        Body: file,
        Key: file.name,
    };
    s3.putObject(params, function (err, data) {
        if (err) {
            console.log(err, err.stack);
        } else {
            alert("文件上传成功!");
            console.log(data);
        }
    });
}

/**
 *  生成临时ak、sk、token，然后生成文件上传预签名地址
 */
function uploadFileByPresignUrl() {
    ajax({
        url: "/xstore-s3-demo/sts/presignedPutUrl",
        async: false,
        dataType: "json",
        data: {key: file.name},
        success: function (response) {
            console.log(response);
            var resp = JSON.parse(response);
            ajax({
                url: resp.url,
                type: "put",
                contentType: "binary/octet-stream",
                data: file,
                dataType: "json",
                header: {'x-amz-acl': 'public-read'},//设置文件的访问权限：所有用户都可以读取
                success: function (responseText, etag) {
                    console.log(etag.replace(/\"/g, ""));
                    alert("使用预签名地址上传文件成功");
                },
                error: function (status) {

                }
            });

        }
    });
}


/**
 * 获取临时ak、sk、sessionToken，创建s3客户端
 * @returns {*}
 */
function createCredentialsS3Client() {
    // 获取临时ak、sk、sessionToken
    if (accessKeyId == "") {
        ajax({
            url: "/xstore-s3-demo/sts/assumeRole",
            async: false,
            dataType: "json",
            success: function (response) {
                var resp = JSON.parse(response);
                accessKeyId = resp.ak;
                secretAccessKey = resp.sk;
                sessionToken = resp.tk;
                endpoint = resp.endpoint;
                bucket = resp.bucket;
            }
        });
    }
    // 创建s3客户端
    var creds = new AWS.Credentials({
        accessKeyId: accessKeyId,
        secretAccessKey: secretAccessKey,
        sessionToken: sessionToken
    });
    return new AWS.S3({
        endpoint: endpoint,
        credentials: creds
    });

}

function createS3Client() {
    return new AWS.S3({
        endpoint: endpoint,
        accessKeyId: accessKeyId,
        secretAccessKey: secretAccessKey
    });
}
